package com.echoesnet.echoesshortvideo.Activities;

import android.arch.lifecycle.Observer;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.echoesnet.echoesshortvideo.R;
import com.echoesnet.echoesshortvideo.Utils.CommonUtils;
import com.echoesnet.echoesshortvideo.ViewModels.StepRegisterViewModel;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginStepRegisterAct extends BaseActivity implements View.OnClickListener
{
    @BindView(R.id.cancle)
    ImageView tvCancle;
    @BindView(R.id.phone)
    TextView phone;

    @BindView(R.id.phone_code)
    EditText editText;
    @BindView(R.id.nextOk)
    ImageView ivNext;
    @BindView(R.id.scrollLayout)
    RelativeLayout rl;
    @BindView(R.id.reSend)
    TextView reSend;
    @BindView(R.id.tvVerify)
    TextView tvVerify;
    @BindView(R.id.reSend_time)
    TextView reSendTime;
    @BindView(R.id.tvVerify_time)
    TextView tvVerifyTime;

    private StepRegisterViewModel lModel;

    //屏幕高度
    private int screenHeight = 0;
    //软件盘弹起后所占高度阀值
    private int keyHeight = 0;
    @BindView(R.id.root_layout)
    View activityRootView;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_login_register_phone);

        ButterKnife.bind(this);
        phone.setText("+86 " + getIntent().getStringExtra("phone"));
        editText.addTextChangedListener(new TextWatcher()
        {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after)
            {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count)
            {
                if (s.length() < 6)
                {
                    ivNext.setClickable(false);
                    ivNext.setAlpha(0.5f);
                } else
                {
                    ivNext.setClickable(true);
                    ivNext.setAlpha(1f);
                }

            }

            @Override
            public void afterTextChanged(Editable s)
            {

            }
        });


        lModel = new StepRegisterViewModel();
        lModel.getLiveData().observe(this, new Observer<String>()
        {
            @Override
            public void onChanged(@Nullable String type)
            {
                if (type == null)
                    return;

                if (type.equals("checkCodeOk"))
                {
                    Intent intent = new Intent(LoginStepRegisterAct.this, RegisterPasswordAct.class);
                    intent.putExtra("phone", phone.getText().toString().replace("+86", "").trim());
                    intent.putExtra("code", editText.getText().toString().trim());
                    new Handler().postDelayed(()->{exitAnim();}, 100);
                    startActivity(intent);
                    overridePendingTransition(R.anim.out_to_bottom, R.anim.out_to_top_abit);
                } else
                {
                    editText.setText(type);
                    Selection.setSelection(editText.getText(), editText.getText().length());
                }

            }
        });
        String code =getIntent().getStringExtra("code");
        if(TextUtils.isEmpty(code))
        {
            lModel.sendVerificationCode(getIntent().getStringExtra("phone"), "0");
            reSend.setEnabled(false);
            reSend.setTextColor(ContextCompat.getColor(this, R.color.v2));
            tvVerify.setEnabled(false);
            tvVerify.setTextColor(ContextCompat.getColor(this, R.color.v2));
            reSendTime.setVisibility(View.VISIBLE);
            ttMsgCountDown = new SecurityCountDown();
            MsgTimer.scheduleAtFixedRate(ttMsgCountDown, 0, 1000);
            ivNext.setClickable(false);
        }else
            editText.setText(code);
        //获取屏幕高度
        screenHeight = CommonUtils.getScreenHeight(this);
        //阀值设置为屏幕高度的1/3
        keyHeight = screenHeight / 3;
        //添加layout大小发生改变监听器
        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(layoutListener);

        Selection.setSelection(editText.getText(), editText.getText().length());


    }

    @OnClick({R.id.cancle, R.id.reSend, R.id.tvVerify, R.id.nextOk,R.id.root_layout})
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.cancle:
                Intent intent = new Intent(this, LoginAct.class);
                intent.putExtra("phone", phone.getText().toString().replace("+86", "").trim());
                startActivity(intent);
                new Handler().postDelayed(()->{exitAnim2();},100);
                overridePendingTransition(R.anim.out_to_top, R.anim.out_to_bottom_abit);
                break;

            case R.id.nextOk:
                if(CommonUtils.isFastDoubleClick())
                {
                    return;
                }
                lModel.checkVerifyCode(phone.getText().toString().replace("+86", "").trim(),
                        editText.getText().toString().trim(), "0");
                break;
            case R.id.reSend:
                //验证码发送
                lModel.sendVerificationCode(phone.getText().toString().replace("+86", "").trim(), "0");

                tvVerify.setEnabled(false);
                tvVerify.setTextColor(ContextCompat.getColor(this, R.color.v2));
                reSend.setEnabled(false);
                reSend.setTextColor(ContextCompat.getColor(this, R.color.v2));
                reSendTime.setVisibility(View.VISIBLE);
                ttMsgCountDown = new SecurityCountDown();
                MsgTimer.scheduleAtFixedRate(ttMsgCountDown, 0, 1000);
                break;
            case R.id.tvVerify:
                //语音验证
                lModel.sendVoiceCode(phone.getText().toString().replace("+86", "").trim(), "0");

                tvVerify.setEnabled(false);
                tvVerify.setTextColor(ContextCompat.getColor(this, R.color.v2));
                reSend.setEnabled(false);
                reSend.setTextColor(ContextCompat.getColor(this, R.color.v2));

                tvVerifyTime.setVisibility(View.VISIBLE);
                ttAudioMsgCountDown = new SoundCodeCountDown();
                AudioTimer.scheduleAtFixedRate(ttAudioMsgCountDown, 0, 1000);
                break;

        }

    }


    @Override
    public void onBackPressed()
    {
        Intent intent = new Intent(this, LoginAct.class);
        intent.putExtra("phone", phone.getText().toString().replace("+86", "").trim());
        startActivity(intent);
        new Handler().postDelayed(()->{exitAnim2();},100);
        overridePendingTransition(R.anim.out_to_top, R.anim.out_to_bottom_abit);

    }

    private void updateViewHeight(boolean flag)
    {
        RelativeLayout.LayoutParams pa = (RelativeLayout.LayoutParams) rl.getLayoutParams();
        pa.topMargin = flag ? LoginAct.TOP_MARGIN : 0;
        rl.setLayoutParams(pa);
    }

    ViewTreeObserver.OnGlobalLayoutListener layoutListener = new ViewTreeObserver.OnGlobalLayoutListener()
    {

        @Override
        public void onGlobalLayout()
        {
            activityRootView.getViewTreeObserver().removeOnGlobalLayoutListener(layoutListener);

            Rect r = new Rect();
            activityRootView.getWindowVisibleDisplayFrame(r);

            //现在认为只要控件将Activity向上推的高度超过了1/3屏幕高，就认为软键盘弹起
            if (screenHeight - r.bottom > keyHeight)
            {
                updateViewHeight(true);
            } else
            {
                updateViewHeight(false);
            }
            activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(layoutListener);
        }
    };

    private void exitAnim()
    {
        Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.out_to_top_abit);
        animation.setDuration(350);
        animation.setFillAfter(true);
        animation.setFillBefore(false);
        animation.setAnimationListener(new Animation.AnimationListener()
        {
            @Override
            public void onAnimationStart(Animation animation)
            {

            }

            @Override
            public void onAnimationEnd(Animation animation)
            {
                finish();
            }

            @Override
            public void onAnimationRepeat(Animation animation)
            {

            }
        });
        activityRootView.startAnimation(animation);

    }
    private void exitAnim2()
    {
        Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.out_to_bottom_abit);
        animation.setDuration(350);
        animation.setFillAfter(true);
        animation.setFillBefore(false);
        animation.setAnimationListener(new Animation.AnimationListener()
        {
            @Override
            public void onAnimationStart(Animation animation)
            {

            }

            @Override
            public void onAnimationEnd(Animation animation)
            {
                finish();
            }

            @Override
            public void onAnimationRepeat(Animation animation)
            {

            }
        });
        activityRootView.startAnimation(animation);

    }


    private TimerTask ttMsgCountDown;
    private TimerTask ttAudioMsgCountDown;
    private Timer MsgTimer=new Timer();
    private Timer AudioTimer=new Timer();
    private int msgCountdown=60;
    private  int  audioCountdown=60;

    /**
     * 验证码倒计时
     */
    private class SecurityCountDown extends TimerTask
    {
        @Override
        public void run()
        {
            runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    reSendTime.setText(String.format("%ss", String.valueOf(msgCountdown--)));
                    if (msgCountdown < 1)
                    {
                        resetGetSecurityButton();
                    }
                }
            });
        }
    }

    /**
     * 重置验证码获取按钮
     */
    private void resetGetSecurityButton()
    {
        tvVerify.setEnabled(true);
        tvVerify.setTextColor(ContextCompat.getColor(this, R.color.MC2));
        reSend.setEnabled(true);
        reSend.setTextColor(ContextCompat.getColor(this, R.color.MC2));
        reSendTime.setVisibility(View.GONE);
        msgCountdown = 60;
        if (ttMsgCountDown != null)
            ttMsgCountDown.cancel();

    }


    /**
     * 语音验证码倒计时
     */
    private class SoundCodeCountDown extends TimerTask
    {
        @Override
        public void run()
        {
            runOnUiThread(new Runnable()
            {
                @Override
                public void run()
                {
                    tvVerifyTime.setText(String.format("%ss", String.valueOf(audioCountdown--)));
                    if (audioCountdown < 1)
                    {
                        resetGetSoundCodeButton();
                    }
                }
            });
        }
    }

    /**
     * 重置验证码获取按钮
     */
    private void resetGetSoundCodeButton()
    {
        tvVerify.setEnabled(true);
        tvVerify.setTextColor(ContextCompat.getColor(this, R.color.MC2));
        reSend.setEnabled(true);
        reSend.setTextColor(ContextCompat.getColor(this, R.color.MC2));
        tvVerifyTime.setVisibility(View.GONE);
        audioCountdown = 60;
        if (ttAudioMsgCountDown != null)
            ttAudioMsgCountDown.cancel();
    }

}
